<?php
namespace App\Admin\Controllers;

use App\Admin\Renderable\AdminTable;
use App\Admin\Repositories\AdminUserGroup;
use App\Models\AdminAd;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Collection;

class AdminUserGroupController extends AdminController
{
    /**
     * Make a grid builder.
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(AdminUserGroup::with('admin'), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('admin.name', trans('admin-user-group.fields.contact'));
            $grid->column('admin.phone', trans('admin.phone')) -> copyable();
            $grid->column('name');
            $grid->column('description');
            $grid->column('file') -> image('',50,50);
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new AdminUserGroup(), function (Show $show) {
            $show->field('id');
            $show->field('user_id');
            $show->field('name');
            $show->field('description');
            $show->field('file');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AdminUserGroup(), function (Form $form) {
            $form->display('id');
            $form->selectTable('user_id',trans('admin-user-group.fields.contact'))
                ->title(trans('admin-user-group.fields.contact'))
                ->dialogWidth('50%') //弹窗宽度，默认 800px
                ->from(AdminTable::make(['id' => $form->getKey()])) //设置渲染类实例，并传递自定义参数
                ->model(Administrator::class, 'id', 'name')
                ->required(); //设置编辑数据显示
            $form->text('name') -> required();
            $form->textarea('description');
            $form->image('file') -> autoUpload();
            $form->display('created_at');
            $form->display('updated_at');
            $form->deleting(
                function (Form $form) {
                    $arr = Collection::make($form -> model());

                    $res = AdminAd::firstWhere(['positions_id' => ['in' => $arr->pluck('id')->toArray()]]);

                    if($res) {
                        return $form->response()->error('已被新闻占用，无法直接删除');
                    }
                }
            );
        });
    }
}
